#include "redisConnector.h"


using namespace easyWebServer;

namespace dxy::easyWebServer
{

RedisConnector & RedisConnector::getInstance()
{
    static RedisConnector instance;
    return instance;
}

void RedisConnector::insert(const std::string & key, const std::string & value)
{
    m_mutex.lock();
    redisContext * redisCtx = redisConnect(m_ip.c_str(), m_port);
        
    redisReply * reply = nullptr;

    reply = (redisReply *)redisCommand(redisCtx, "auth %s", m_passward.c_str());
    freeReplyObject(reply);
    reply = nullptr;

    reply = (redisReply *)redisCommand(redisCtx, "set %s %s", key.c_str(), value.c_str());
    freeReplyObject(reply);
    reply = nullptr;
    
    redisFree(redisCtx);
    m_mutex.unlock();
}

void RedisConnector::del(const std::string & key)
{
    m_mutex.lock();
    redisContext * redisCtx = redisConnect(m_ip.c_str(), m_port);
        
    redisReply * reply = nullptr;

    reply = (redisReply *)redisCommand(redisCtx, "auth %s", m_passward.c_str());
    freeReplyObject(reply);
    reply = nullptr;

    reply = (redisReply *)redisCommand(redisCtx, "del %s", key.c_str());
    freeReplyObject(reply);
    reply = nullptr;
    
    redisFree(redisCtx);
    m_mutex.unlock();
}

std::string RedisConnector::get(const std::string & key)
{
    redisContext * redisCtx = redisConnect(m_ip.c_str(), m_port);
        
    redisReply * reply = nullptr;

    reply = (redisReply *)redisCommand(redisCtx, "auth %s", m_passward.c_str());
    freeReplyObject(reply);
    reply = nullptr;

    reply = (redisReply *)redisCommand(redisCtx, "get %s", key.c_str());
    std::string ret(reply->str);
    freeReplyObject(reply);
    reply = nullptr;
    
    redisFree(redisCtx);
    return ret;
}

std::vector<std::string> RedisConnector::keys()
{
    redisContext * redisCtx = redisConnect(m_ip.c_str(), m_port);
    if(!redisCtx)
    {
        // throw std::runtime_error("redisConnect error");
        return std::vector<std::string>();
    }
        
    redisReply * reply = nullptr;

    reply = (redisReply *)redisCommand(redisCtx, "auth %s", m_passward.c_str());
    freeReplyObject(reply);
    reply = nullptr;

    reply = (redisReply *)redisCommand(redisCtx, "keys *");
    std::vector<std::string> ret;
    for(int i = 0; i < reply->elements; i++)
    {
        ret.push_back(std::string(reply->element[i]->str));
    }
    freeReplyObject(reply);
    reply = nullptr;
    
    redisFree(redisCtx);
    return ret;
}

RedisConnector::RedisConnector()
{
    m_ip = slt(Json)["redis_ip"].asString().c_str();
    m_port = slt(Json)["redis_port"].asInt();
    m_passward = slt(Json)["redis_password"].asString();
}

RedisConnector::~RedisConnector()
{

}

}

